
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyExample {
	interface Car {
		void running();
	}

	static class Bus implements Car {

		@Override
		public void running() {
			System.out.println("Bus is running");
		}
	}

	static class Taxi implements Car {
		@Override
		public void running() {
			System.out.println("Taxi is running");
		}
	}

	/**
	 * JDK Proxy
	 */
	static class JDKProxy implements InvocationHandler {
		private Object target;

		// 获取到代理对象
		public Object getInstance(Object target) {
			this.target = target;
			return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
		}

		/**
		 * 执行代理方法
		 *
		 * @param proxy 代理对象
		 * @param method 方法
		 * @param args 参数
		 * @return Object 返回代理之后的实例
		 * @throws Throwable 抛出异常
		 */
		@Override
		public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
			// do something...
			System.out.println("动态代理之前的业务处理.");
			return method.invoke(target, args);
		}
	}

	public static void main(String[] args) {
		JDKProxy jdkProxy = new JDKProxy();
		Car car = (Car) jdkProxy.getInstance(new Taxi());
		car.running();
	}
}
